package com.huajx.cseek.face.handler;

import com.ha.facecamera.configserver.pojo.Face;
import com.huajx.core.handler.HandlerAdapter;
import com.huajx.core.message.RequestMessage;
import com.huajx.core.message.ResponseMessage;
import com.huajx.cseek.face.FaceCommand;
import com.huajx.cseek.face.server.CseekConfigServer;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.mina.core.session.IoSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class AddFaceHandler implements HandlerAdapter {
    private static final Logger logger = LoggerFactory.getLogger(AddFaceHandler.class);
    private List<FaceCommand> renderCommans = new ArrayList<>();

    @Override
    public ResponseMessage handler(RequestMessage request) {
        JSONArray json = JSONArray.fromObject(request.getMessage());

        List<FaceCommand> commans = new ArrayList<>();
        if (json.size() > 0) {
            for (int i = 0; i < json.size(); i++) {
                JSONObject job = json.getJSONObject(i);   // 遍历 jsonarray 数组，把每一个对象转成 json 对象
                FaceCommand command = new FaceCommand();
                command.setApparatusId(job.getString("apparatusId"));
                command.setFaceid(job.getString("faceid"));
                command.setName(job.getString("name"));
                command.setCommand(job.getString("command"));
                command.setRole(job.getInt("role"));

                JSONArray photos = job.getJSONArray("path");
                String[] paths = new String[photos.size()];
                for (int j = 0; j < photos.size(); j++) {
                    paths[j] = photos.getString(j);
                }

                command.setPath(paths);

                commans.add(command);
            }
        }

        renderCommans = executeCommand(commans);
        return null;
    }

    @Override
    public void render(IoSession session) {
        JSONArray array = JSONArray.fromObject(renderCommans);
        session.write(array);
    }


    /**
     * 执行人脸机服务
     *
     * @param list 命令列表
     */
    public List<FaceCommand> executeCommand(List<FaceCommand> list) {
        List<FaceCommand> renderCommand = new ArrayList<>();
        for (FaceCommand faceCommand : list) {
            String command = faceCommand.getCommand();
            boolean flag = false;
            if ("save".equals(command)) {
                flag = CseekConfigServer.addFace(faceCommand);

            } else if ("update".equals(command)) {
                flag = CseekConfigServer.modifyFace(faceCommand);
            } else if ("delete".equals(command)) {
                flag = CseekConfigServer.deleteFace(faceCommand);
            } else if ("read".equals(command)) {
                readFaceInfo(faceCommand, renderCommand);

                flag = renderCommand.size() == 0;
            }
            if (flag) {
                renderCommand.add(faceCommand);
            }
        }
        logger.info("命令返回集合" + renderCommand.size());
        return renderCommand;
    }

    /**
     * 读取人脸头像集合
     *
     * @param faceCommand   人脸信息
     * @param renderCommand 重构后人脸
     */
    public void readFaceInfo(FaceCommand faceCommand, List<FaceCommand> renderCommand) {
        List<Face> faces = new ArrayList<>();
        String sn = faceCommand.getApparatusId();
        CseekConfigServer.getFaces(sn, null, faces);
        if (faces.isEmpty()) {
            logger.info("获取到人脸数据为空！");
            return;
        }
        for (Face face : faces) {
            String[] paths = faceInfoPhotoUpload(face.getThumbImageData());
            String faceid = face.getId();//学生人脸id
            String name = face.getName();//学生名称
            String commandStr = faceCommand.getCommand();//命令字符串
            String apparatusId = faceCommand.getApparatusId();
            FaceCommand command = new FaceCommand();
            command.setCommand(commandStr);
            command.setPath(paths);
            command.setRole(face.getRole());
            command.setFaceid(faceid);
            command.setApparatusId(apparatusId);
            command.setName(name);
            logger.info("获取到学号为{}人脸数据！", faceid);
            renderCommand.add(command);
        }
    }

    /**
     * 将人脸头像存入七牛云
     *
     * @param thumbImageData
     */
    public String[] faceInfoPhotoUpload(byte[][] thumbImageData) {
        String[] paths = new String[thumbImageData.length];
        for (int i = 0; i < thumbImageData.length; i++) {
            long time = new Date().getTime();
            byte[] data = thumbImageData[i];
            try {
                //QnyfUpload qnyfUpload = new QnyfUpload(null, null, null, null);
                //String facePath = qnyfUpload.upload(data, String.valueOf(time) + ".jpg");
                String facePath = "face-" + time + ".jpg";
                paths[i] = facePath;
                logger.info("将人员头像存储在七牛云成功！图像地址{}", facePath);
            } catch (Exception e) {
                logger.info("从人脸相机上拉取数据失败！", e);
            }
        }
        return paths;
    }
}
